<template>
	<div class="login-container">
		<van-nav-bar
		  title="登录"
		  left-arrow
			@click-left="$router.back()"
		/>
		<van-form @submit="onLogin" :show-error="false" :show-error-message="false" ref="login-form" validate-first>
		  <van-field
		    v-model="user.mobile"
		   
		    left-icon="phone-circle-o"
				name="mobile"
		    placeholder="请输入手机号"
				:rules="formRules.mobile"
		  />
		  <van-field
		    v-model="user.code"
		    clearable
		    left-icon="browsing-history-o"
				name="code"
		    placeholder="请输入验证码"
				:rules="formRules.code"
		  >
			 <template #button>
				 <van-count-down :time="1000 * 60" format="ss s" v-if="isCountDowShow" @finish="isCountDowShow = false"/>
			    <van-button size="mini" round class="backgroud" @click.prevent="onSendSms" v-else :loading="isSendSmsLoading">发送验证码</van-button>
					
			  </template></van-field>
				<div class="login-btn-wrap">
					<van-button type="info" block @click="onLogin">登录</van-button>
				</div>
		</van-form>
		
		
	</div>
</template>

<script>
	import {login} from '../../utils/user.js'
	import {Toast} from 'vant'
	
	export default {
		name:'LoginIndex',
		data() {
			return {
				user:{
					mobile:'17090086870',//手机号
					code:'246810'
				},
				formRules: {
					mobile:[
						{ required: true, message: '请输入手机号' },
						{pattern:/^1{3|5|7|8}\d{9}$/,message: '手机号格式错误'}
					],
					code:[
						{ required: true, message: '请输入验证码' },
						{pattern:/^\d{6}$/,message: '验证码错误'}
					]
				},
				isCountDowShow:false,
				isSendSmsLoading:false
			}
		},
		methods:{
			async onLogin() {
				Toast.loading({
				  message: '登录中...',
				  forbidClick: true,
					duration:0
				});
				try {
					const res = await login(this.user)
					
					this.$toast.success('登陆成功');
					
					this.$store.commit('setUser',res.data.data)
					
					this.$store.commit('removeCachePage','Layout')
					
					this.$router.back()
					
				} catch(err) {
					/* console.log('登录失败,17090086870,246810') */
					this.$toast.fail('登录失败');
					
				}
				
			},
			async onSendSms() {
				try {
					const validateRet = await this.$refs['login-form'].validate('mobile')
					this.isCountDowShow = true
					this.isSendSmsLoading = true
				}catch(err) {
					console.log('验证失败',err)
					this.$toast({
						message:err.message,
						position:'top'
					})
				}
				this.isSendSmsLoading = false
				
			}
		}
	}
</script>

<style scoped>
	.login-btn-wrap {
		padding: 26px 16px;
	}
	.backgroud {
		background-color: #f5f5f5;
	}
</style>
